# encoding=utf-8
import logging
import re
import urllib2

from django.db import models

from comm import util


logger = logging.getLogger('apps')


class Entity(models.Model):
    id = models.AutoField(primary_key=True)
    key = models.CharField(max_length=36)
    val = models.CharField(max_length=36)
    
    def __str__(self):  # for str() return
        return "%d %s %s" % (self.id, self.key, self.val);
    
    def __unicode__(self):  # for unicode(), django db backends return unicode in model attributes,when invoke str(),if __str__ is not exist,is call __unicode__ instead;
        return "%d %s %s" % (self.id, self.key, self.val);
    
    # meta类来修改ADMIN后台显示的模块名称,数据库相关信息
    class Meta:
        db_table = 'tb_entity'  # 数据库表名
        ordering = ['id']
        verbose_name = u'meta'  # 页面导航栏展示
        verbose_name_plural = u'collection'  # 上级连接展示
        
        
class RingWeb(models.Model):
    id = models.CharField(primary_key=True, max_length=36)
    name = models.CharField(max_length=128)
    artist = models.CharField(max_length=128)
    duration = models.CharField(max_length=128)
    playcnt = models.CharField(max_length=36)
    
    status = models.CharField(max_length=128)
    
    mask_download_file = 1
    
    file_prefix = 'D:/Users/usr/Desktop/ring/'
    
    download_urlf = 'http://www.shoujiduoduo.com/ringweb/ringweb.php?type=geturl&act=down&rid={rid}'
    
    '''
    mask start with 1
    '''
    def get_status(self, mask):
        if len(self.status) >= mask:
            self.status[mask - 1]
        else :
            return 0
        
    '''
    mask start with 1
    '''
    def set_status(self, mask, value):
        length = len(self.status)
        if length >= mask:
            self.status = self.status[0:mask - 1] + str(value) + self.status[mask:]
        else:
            padding = mask - length - 1
            self.status = self.status + '0' * padding + str(value)
            
    def download(self, *args, **kwargs):
        try:
            download_url = RingWeb.download_urlf.format(rid=self.id)
            rsp = urllib2.urlopen(download_url).read()
            logger.info(rsp)
            if len(rsp) > 0:
                fr = re.match(r'(.*)filename=(.*)$', rsp)
                file_sub_name = None
                if fr :
                    rsp = fr.group(1) + urllib2.quote(fr.group(2))
                    file_sub_name = fr.group(2)
                filename = RingWeb.file_prefix + str(self.id) + '_' + file_sub_name
                req = urllib2.Request(url=rsp)
                f = urllib2.urlopen(req)
                fname = filename.decode('utf-8')
                if not util.checkfile(fname):
                    with open(fname , 'wb') as code:
                        code.write(f.read())
                self.set_status(RingWeb.mask_download_file, 1)
        except:
            logger.info(' download faile id ' + str(self.id))
            self.set_status(RingWeb.mask_download_file, 2)
        
        self.save()
    
    def __unicode__(self):
        return "%s %s %s %s %s" % (self.id, self.name, self.artist, self.duration, self.playcnt)
    
    class Meta:
        db_table = 'tb_ring'
        ordering = ['id']
        verbose_name = u'meta'  # 页面导航栏展示
        verbose_name_plural = u'RingWeb'  # 上级连接展示
        

class SystemConfig(models.Model):
    id = models.IntegerField(primary_key=True)
    key = models.CharField(unique=True, max_length=64)
    value = models.CharField(max_length=32)
    
    def __unicode__(self):
        return "%s %s %s" % (self.id, self.key, self.value)
    
    class Meta:
        db_table = 'tb_system_config'
        ordering = ['id']
        verbose_name = u'meta'  # 页面导航栏展示
        verbose_name_plural = u'SystemConfig'  # 上级连接展示
    
    
    
    


        
